package kjj.test.bluetooth.sample.clientserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.bluetooth.*;
import javax.microedition.io.*;
/**
 * Class that implements an SPP Server which accepts single line of
 * message from an SPP client and sends a single line of response to the client.
 */
public class BluetoothSppServer {
	//debugging
	private static final boolean D =true;
	private static final String TAG = "BluetoothSppServer: ";
	
	//start server
	private void startServer() throws IOException{
		//Create a UUID for SPP
		//UUID uuid = new UUID("1101", true);
		UUID uuid = new UUID("c9751ff0813d11e1b0c40800200c9a66", false);
		if (D) {
			System.out.println(TAG + uuid.toString());
		}
		
		//Create the servicve url
		String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
		if (D) {
			System.out.println(TAG + connectionString);
		}
		
		//open server url
		StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
		while (true){
			//Wait for client connection
			System.out.println("\nServer Started. Waiting for clients to connect...");
			try {
				StreamConnection connection=streamConnNotifier.acceptAndOpen();
				ConnectedThread worker = new ConnectedThread(connection);
//				worker.run();
				worker.start();
			} catch (IOException e) {
				// TODO: handle exception
				if (D) {
					System.out.println(TAG + "IOException");
				}
				break;
			}
		}
	
		streamConnNotifier.close();
	}
	public static void main(String[] args) throws IOException {
		//display local device address and name
		LocalDevice localDevice = LocalDevice.getLocalDevice();
		System.out.println("Address: "+localDevice.getBluetoothAddress());
		System.out.println("Name: "+localDevice.getFriendlyName());
		BluetoothSppServer sampleSPPServer=new BluetoothSppServer();
		sampleSPPServer.startServer();
	}
}


